/**
* 创建者：luyiming
* 该页面用于：
* 创建时间： 2020-03-06 21:48:11
*/
import Table from "@/components/Table";
import Pagination from "@/components/Pagination"; // 分页
import ReportTable from "@/components/luyiming/ReportTable/index.vue";
import { getDelarationList, reportType, reportDetial, entDetial, InsertDeclareNewRad, getRadUsed } from "@/api/RCIM/RCIM-addandstorage";
import { cloneDeep } from "lodash";
import moment from "moment";
export default {
    name: 'RcimAddandstorageDeclaration_view',
	components: {
		Table,
		Pagination,
		ReportTable,
	},
    // 数据
    data() {
        return {
            tableData: [],
			tableHead: [{
					prop: "registrant",
					label: "登记人",
					width: "",
					align: "center"
				},
				{
					prop: "leadingCadre",
					label: "企业负责人",
					width: "",
					align: "center"
				},
				{
					prop: "reportingTime",
					label: "申报时间",
					width: "",
					align: "center"
				},
				{
					prop: "reportType",
					label: "申报类型",
					width: "",
					align: "center"
				},
				{
					prop: "operate",
					label: "操作",
					width: "",
					align: "center"
				}
			],
			listLoading: false,
			total: 0,
			listQuery: {
				page: 1,
				limit: 10,
				type: '1',
			},
			dialogFormVisible: false,
			timeParam: [
				moment().subtract(1, 'months').format('YYYY-MM-DD'),
				moment().format('YYYY-MM-DD')
			],
			reportTable: [
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '企业名称',
						key: 'name',
						disable: true,
					}]
                },
				{
					col: [{
						fspan: 24,
						span: [24, 0],
						name: '放射源（单位/枚）',
						key: null,
					}]
				},
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '源用途',
						key: 'radusedid',
						required: true,
						formType: 'select',
						formTypeC: 'option',
						options: []
					}]

                },
				{
					col: [{
						fspan: 12,
						span: [12, 12],
						name: '登记人：',
						key: 'registrant',
						disable: true,
					},{
						fspan: 12,
						span: [12, 12],
						name: '企业负责人：',
						key: 'chargePerson',
						disable: true,
					}]
				},
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '申报日期：',
						key: 'declareTime',
						required: true,
						formType: 'date-picker',
					}]

				},
			],
			newSourceReport: [
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '新增源数',
						key: 'newSourceNum',
                        disable: true,
                        showAfter: true,
					}]

                },
			],
			stroageReport: [
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '收贮源数',
						key: 'stroageSourceNum',
						disable: true,
                        showAfter: true,
					}]

				},
			],
			newSourceForm:[],
			storageSourceForm:[],
			reportSourceTitle: "放射源新增申请表",
			reportStroageTitle: "放射源收贮申请表",
			isShowNewSourceReport: false,
			entData: null,
			isReadOnly: false,
			reportLoading: false,
			sourceAddRule: {
				radusedid: [
					{required: true, message: '请输入源用途'}
				],
				declareTime: [
					{required: true, message: '请选择申报日期'}
				]
			},
			// sourceStorageRule: {

			// }
        }
    },
    // 监听
    watch: {

    },
    // Vue实例初始化完成
    created() {
		getRadUsed().then(res => {
			this.reportTable.splice(2, 1,
				{
					col: [{
						fspan: 24,
						span: [6, 18],
						name: '源用途',
						required: true,
						key: 'radusedid',
						formType: 'select',
						formTypeC: 'option',
						options: res.data
					}]
				}
			)
			this.newSourceForm = cloneDeep(this.reportTable);
			this.newSourceForm.splice(2,0,...cloneDeep(this.newSourceReport));
			this.storageSourceForm = cloneDeep(this.reportTable);
			this.storageSourceForm.splice(2,0,...cloneDeep(this.stroageReport));
		})

    },
    // Vue挂载完成
    mounted() {
		this.search()
		this.entData = this.entInfo()
    },
    // Vue实例销毁前
    beforeDestroy(){

	},
	// 监听
	watch: {
		'listQuery.type'() {
			Object.assign(this.listQuery, {
				page: 1,
				limit: 10
			})
			this.search()
		}
	},
    // 挂载的方法
    methods: {
        /**
        * 方法描述
        */
        exampleFunc(){
            return void 0
		},
		/**
		 * @desc 获取数据
		 */
		getList(){
			// 调用接口数据
			return getDelarationList(
				this.listQuery
			).then(res => {
				this.total = res.data.total;
				this.tableData = res.data.data;
			})
		},
		/**
		 * @desc 搜索表格数据
		 */
        search() {
			this.listLoading = true;
			if(this.timeParam.length !== 0){
				this.listQuery.startTime = moment(this.timeParam[0]).format('YYYY-MM-DD')
				this.listQuery.endTime = moment(this.timeParam[1]).format('YYYY-MM-DD') + ' 23:59:59'
			}
			this.getList().then(res => {
				this.listLoading = false;
			}).catch(e => {
				this.listLoading = false;
			})
		},
		/**
		 * @desc 打开弹窗
		 */
        openDialog() {
			this.dialogFormVisible = true
		},
		/**
		 * @desc 获取表格信息
		 * @returns 数据
		 */
		entInfo(){
			return entDetial({
			}).then(res => {
				return res?.data?.entData ?? {}
			})
		},
		/**
		 * @desc 源新增申报/源收贮申报 新增
		 * @param {Boolean} vol 判断（源新增申报/源收贮申报）新增
		 */
        addReport(vol){
            this.openDialog();
            this.isShowNewSourceReport = vol;
			this.isReadOnly = false;
            this.entData.then(res => {
                if(this.isShowNewSourceReport){
					console.log(this.$refs.reportSource, this.$refs.reportSource.setDefaultValue)
					// 调用组件内置方法
                    this.$refs.reportSource.setDefaultValue(Object.assign(cloneDeep(res), {
                        newSourceNum: 1,
                        code__0: '',
                    }))
                }else{
                    this.$refs.reportDevice.setDefaultValue(Object.assign(cloneDeep(res), {
                        stroageSourceNum: 1,
                        code__0: '',
                    }))
                }
            })
		},
		/**
		 * @desc 关闭弹窗
		 */
        handleClose(){
			this.dialogFormVisible = false
		},
		/**
		 * @desc 查看数据
		 * @param {Object} row 
		 */
        async handleFind(row){
            this.openDialog();
			// reportType 为1是为新增
			this.reportLoading = true;
            this.isShowNewSourceReport = row.reportType === '新增';
			this.isReadOnly = true;
			// 调用接口
            const detialData = await reportDetial({
                id: row.id,
                type: row.reportType,
            }).then(res => {
                const result = res.data.detialData;
                result.countryCode.split(',').forEach((itemV, inde) => {
                    result['code__' + inde] = itemV;
                })
                delete result.countryCode;
                return result
            })
            this.entData.then(res => {
                if(this.isShowNewSourceReport){
					console.log(this.$refs.reportSource, this.$refs.reportSource.setDefaultValue)
					// 旧 this.$refs.reportSource.setDefaultValue(res, detialData)
                    this.$refs.reportSource.setDefaultValue(Object.assign(cloneDeep(res), detialData))
                }else{
                    this.$refs.reportDevice.setDefaultValue(Object.assign(cloneDeep(res), detialData))
				}
				this.reportLoading = false;
            })
		},
		/**
		 * @desc 提交表单数据
		 */
        async submitReport(){
			let type = 0;
			let sendData = null;
			// 判断提交哪种表单
			if(this.$refs.reportSource){
				type = 1;
				sendData = cloneDeep(this.$refs.reportSource?.submitTable() || {})
				sendData.stroageSourceNum = '';
				sendData.type = 1;
			}
			if(this.$refs.reportDevice){
				type = 2;
				sendData = cloneDeep(this.$refs.reportDevice?.submitTable() || {})
				sendData.newSourceNum = '';
				sendData.type = 2;
			}
			let issucesSourceGo = true
			
			if(sendData){
				const kys = Object.keys(sendData).filter(itemKey => /code/.test(itemKey))
				if(!sendData.code__0 || kys.length !== Number(sendData.newSourceNum)) {
					this.$message({
						message: '请补全源国家编码',
						type: 'warning'
					})
					return
				}
				// 验证表单
				issucesSourceGo = await this.$refs.reportSource?.validForm(sendData, this.sourceAddRule).then(valid => valid);
				if(issucesSourceGo) {
					sendData.countryCode = kys.map(item => sendData[item]).join(',')
					// 删除垃圾数据
					kys.concat(['name', 'entid', 'chargePerson', 'registrant', 'sourceNum']).forEach(item => {
						delete sendData[item]
					})
					sendData.declareTime = moment(sendData.declareTime).format('YYYY-MM-DD')
					// 调用新增接口
					InsertDeclareNewRad(sendData).then(res => {
						const strValue = type === 1 ? '放射源新增' : '放射源收贮';
						if(res.code === 200){
							this.search()
							this.handleClose()
							return this.$message.success(`${strValue}申报成功`);
						}
						throw new Error(`${strValue}申报失败`)
					}).catch(error => {
						this.$message.error(error)
					})
				}

			}


        }
    },
}
